/*
 * clickcheckout.java
 *
 * Created on March 26, 2007, 7:11 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.actions;

import javax.servlet.http.*;
import edu.byu.isys413.group1E.data.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.*;
import javax.mail.*;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Authenticator;

/**This action posts the transaction to the Database, and bills the customer
 *
 * @author Kendall Frazier
 */
public class completetransaction implements edu.byu.isys413.web.Action {
    
    /**
     * Creates a new instance of clickcheckout
     */
    public completetransaction() {
    }
    
    /**
     *Processes this method saves the current transaction to the database.  It calls the Update controller to make sure the complicated
     *transaction object is saved correctly.  After this is done, it creates a blank transaction with the appropriate date, customer info,
     *and store info.  This new blank transaction is saved over the old one in the session.  Then an email is sent to the customer
     *to confirm thier order.
     *
     *@param HttpServletRequest
     *@param HttpServletResponse
     *
     *@return String the name of the jsp to call
     */
    public String process(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        TransactionDAO TXDAO = TransactionDAO.getInstance();
        PaymentDAO payDAO = PaymentDAO.getInstance();
        TransLineDAO TLDAO = TransLineDAO.getInstance();
        UpdateController updateController = UpdateController.getInstance();
        CustomerBO custBO = (CustomerBO)session.getAttribute("customer");
        StoreBO storeBO = (StoreBO)session.getAttribute("store");
        MembershipBO membBO = custBO.getCustMembership();
        
        //read in the Transaction from the session
        TransactionBO TXBO = (TransactionBO)session.getAttribute("TX");
        PaymentBO payBO = payDAO.create();
        payBO.setPmtAmount(TXBO.getTransTotal());
        payBO.setType("credit card");
        TXBO.setPmt(payBO);
        //post the Transaction
        updateController.post_sale(TXBO);
        //refresh the cutomer data
        membBO = MembershipDAO.getInstance().read(membBO.getMembershipID());
        custBO.setCustMembership(membBO);
        session.setAttribute("customer",custBO);
        
        //send email
        Properties props = new Properties();
        // fill props with any information
        props.put("mail.smtp.host" ,"gateway.byu.edu");
        // fill props with any information
        Authenticator auth = new MyAuthenticator();
        Session mailSession = Session.getDefaultInstance(props, auth);
        
        MimeMessage message = new MimeMessage(mailSession);
        
        try{
            message.setText("Dear "+custBO.getCustFullName()+": "+"\n"+"Your order has been succesfully processed."+
                    "\n"+"The Total is: $"+TXBO.getTransTotal());
            message.setSubject("MyStuff Order Confirmation");
            Address address1 = new InternetAddress("confirmation@mystuff.com");
            Address address3 = new InternetAddress("kckern11@gmail.com");
            Address address4 = new InternetAddress("kendall.frazier@gmail.com");
            Address address2 = new InternetAddress(custBO.getCustEmail());
            message.setFrom(address1);
            message.addRecipient(Message.RecipientType.TO, address2);
            message.addRecipient(Message.RecipientType.TO, address3);
            message.addRecipient(Message.RecipientType.TO, address4);
            
            Transport.send(message);
            
            ArrayList <TransLineBO> txLineList = TXBO.getTxLineList();
            //rental email to store phone
            String type = txLineList.get(0).getTypeRS();
            if (type.equals("rental")) {
                for (int i = 0; i < txLineList.size(); i++) {
                    RentalBO rbo = (RentalBO)txLineList.get(i).getRevSrc();
                    message.setText("Item # " + rbo.getProduct().getProductID()+": "+"\n"+"Has been reserved by " + custBO.getCustFullName() + " and needs to be set aside for pickup.");
                    Address address5 = new InternetAddress("4805408506@vtext.com"); 
                    message.addRecipient(Message.RecipientType.TO, address5);
                    message.setFrom(address1);
                    
                    Transport.send(message);
                    
                }
            }
            
//        message.saveChanges(); // implicit with send()
//        Transport transport = mailSession.getTransport("smtp");
//        transport.connect("gateway.byu.edu", "frazier", "frazier1827");
//        transport.sendMessage(message, message.getAllRecipients());
//        transport.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        
        //this is the precident for clearing the transaction
        TXBO = TXDAO.create();
        CustomerBO customer = (CustomerBO)session.getAttribute("customer");
        TXBO.setCustomerID(customer.getCustID());
        TXBO.setStoreID("0000011106a3cc370000007f000002");
        TXBO.setEmployeeID("0000011106a3cc390000007f000002");
        //set the date for the transaction
        Calendar cal = Calendar.getInstance();
        Date today = cal.getTime();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = fmt.format(today);
        TXBO.setTransDate(todayDate);
        
        request.setAttribute("TX", TXBO);
        
        session.setAttribute("TX", TXBO);
        
        return "confirmorder.jsp";
    }//process
    
    
}//clickcheckout class
